/*
 * @Descripttion:
 * @version:
 * @Author: caiailing
 * @Date: 2023-03-29 14:42:43
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-04-07 15:48:47
 */
import { defineStore } from 'pinia'
// import type { UserState } from './types'
import {
  getUserInfo,
  login as userLogin,
  logout as userLogout
} from '@/api/apiUser'
import { clearToken, getToken, setToken } from '@/utils/auth'
export default defineStore({
  id: 'user',
  state: (): User.UserInfo => ({
    tokenId: getToken(), // token
    userId: undefined, // 用户id
    roles: [], // 角色
    code: undefined,
    email: undefined,
    name: undefined, // 用户名称
    phone: undefined, // 手机号码
    powerCard: undefined, // 电卡号码
    roleName: undefined,
    laboratory: undefined,
    uri: undefined, // 用户头像
    roleId: undefined, // 基础角色id
    departId: undefined, // 机构Id
    departName: undefined, // 机构Name
    departLevel: undefined, // 机构level
    remark: undefined, // 备注,
    tabBarActiveIndex: 0 // tabbar选中索引值
  }),
  getters: {
    isLogin: (state: User.UserInfo) => {
      const { tokenId, userId } = state
      return !!(tokenId && userId)
    },
    userProfile(state: User.UserInfo): User.UserInfo {
      return { ...state }
    }
  },
  actions: {
    changeTabBarActiveIndex(value: number) {
      this.$state.tabBarActiveIndex = value
    },
    setUserInfo(partial: Partial<User.UserInfo>) {
      this.$patch(partial)
    },
    // 异步登录并存储token
    async login(loginForm: PostLogin.data) {
      const result = await userLogin(loginForm)
      const sessionId = result?.sessionId
      if (sessionId) {
        setToken(sessionId)
      }
    },
    async userInfo(params: {}) {
      const result = await getUserInfo(params)
      const userInfo = result?.userInfo
      if (userInfo) {
        this.setUserInfo({
          tokenId: getToken(), // token
          userId: userInfo?.id, // 用户id
          roles: userInfo?.roles, // 角色
          code: userInfo?.code,
          email: userInfo?.email,
          name: userInfo?.name, // 用户名称
          phone: userInfo?.phone, // 手机号码
          powerCard: userInfo?.powerCard, // 电卡号码
          roleName: userInfo?.roleName,
          laboratory: userInfo?.laboratory,
          uri: userInfo?.uri, // 用户头像
          roleId: userInfo?.roleId, // 基础角色id
          departId: userInfo?.departId, // 机构Id
          departName: userInfo?.departName, // 机构Name
          departLevel: userInfo?.departLevel, // 机构level
          remark: userInfo?.remark // 备注
        })
      }
    },
    // Logout
    async logout() {
      await userLogout({})
      this.resetInfo()
      clearToken()
      // 路由表重置
      // location.reload();
    },
    // 重置用户信息
    resetInfo() {
      this.$reset()
    }
  }
})
